<?php

namespace app\admin\model;

use fast\Tree;
use think\Db;
use think\Model;

class UserRule extends Model
{

    // 表名
    protected $name = 'user_rule';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'status_text'
    ];

    protected static function init()
    {
        self::afterInsert(function ($row) {
            if (!$row['weigh']) {
                $pk = $row->getPk();
                $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            }
        });
    }

    public function getTitleAttr($value, $data)
    {
        return __($value);
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }

    public static function getTreeList($selected = [])
    { 

        // 1. 获取所有目录（请根据实际表名调整）
        $dirs = Db::name('directory')->order('id desc')->select();

        // 2. 获取所有文件
        $files = Db::name('file')->select();

        // 3. 构建父子关系树（手动）
        $tree = [];
        $map = [];

        // 第一步：把所有目录放入 map，并初始化 children
        foreach ($dirs as &$dir) {
            $dir['children'] = [];
            $map[$dir['id']] = &$dir;

            $pid = $dir['pid'] ?? 0;
            $pid = $pid ?: 0;

            if ($pid == 0) {
                // 根节点
                $tree[] = &$dir;
            } else {
                // 放入父节点的 children
                if (isset($map[$pid])) {
                    $map[$pid]['children'][] = &$dir;
                } else {
                    // 父节点不存在，也作为根节点（防止丢失）
                    $tree[] = &$dir;
                }
            }
        }
        unset($dir); // 断开引用

        // 4. 收集所有“有子节点的目录ID”，用于 selected 判断
        $hasChildrens = [];
        $collectHasChild = function ($items) use (&$collectHasChild, &$hasChildrens) {
            foreach ($items as $item) {
                if (!empty($item['children'])) {
                    $hasChildrens[] = $item['id'];
                    $collectHasChild($item['children']);
                }
            }
        };
        $collectHasChild($tree);

        // 5. 遍历树，生成最终 nodeList
        $nodeList = [];

        $traverse = function ($items) use (&$traverse, &$nodeList, $files, $selected, $hasChildrens) {
            foreach ($items as $item) {
                $dirId = $item['id'];
                $parentId = ($item['pid'] ?? 0) ? "{$item['pid']}" : '#';

                // 添加目录节点
                $nodeList[] = [
                    'id'     => "{$dirId}",
                    'parent' => $parentId,
                    'text'   => $item['name'],
                    'type'   => 'directory',
                    'state'  => [
                        'selected' => $parentId == '#' ? false : in_array("{$dirId}", $selected) && !in_array($dirId, $hasChildrens)
                    ]
                ];

                // 添加该目录下的所有文件
                foreach ($files as $file) {
                    if ($file['directory_id'] == $dirId) {
                        $fileId = "{$file['id']}";
                        $nodeList[] = [
                            'id'     => $fileId,
                            'parent' => "{$dirId}",
                            'text'   => $file['filename'],
                            'type'   => 'file',
                            'state'  => [
                                'selected' => in_array($fileId, $selected)
                            ]
                        ];
                    }
                }

                // 递归处理子目录
                if (!empty($item['children'])) {
                    $traverse($item['children']);
                }
            }
        };

        $traverse($tree);

        return $nodeList;
    }

}
